﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace Digitalmes.Infrastructure.Extensions;

/// <summary>
/// JSON 扩展。
/// </summary>
public static class JsonExtensions
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        AllowTrailingCommas = true,
        PropertyNameCaseInsensitive = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        ReadCommentHandling = JsonCommentHandling.Skip,
    };

    private static readonly JsonSerializerOptions JsonOptions2 = new()
    {
        WriteIndented = true,
        AllowTrailingCommas = true,
        PropertyNameCaseInsensitive = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        ReadCommentHandling = JsonCommentHandling.Skip,
    };

    /// <summary>
    /// JSON 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T? FromJson<T>(this string json) where T : class, new() =>
        JsonSerializer.Deserialize<T>(json, JsonOptions);

    /// <summary>
    /// JSON 序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <param name="writeIndented">是否采用缩进格式来打印 JSON 数据。</param>
    /// <returns></returns>
    public static string ToJson<T>(this T obj, bool writeIndented = false) where T : class, new()
    {
        JsonSerializerOptions jsonOptions = writeIndented ? JsonOptions2 : JsonOptions;
        return JsonSerializer.Serialize(obj, jsonOptions);
    }
}
